package algorithm.pool;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.TimeUnit;

public class ConnectionDriver {
    static class ConnectionHandler implements InvocationHandler{
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if(method.getName().equals("commit")){
                TimeUnit.MILLISECONDS.sleep(100);
            }
            System.out.println(proxy.getClass().getName());
            return method.invoke(proxy, null);
        }
    }

    /**
     * 创建一个Connection的代理，在commit时休眠100毫秒
     * @return
     */
    public static final Connection createConnection(){
        return (Connection) Proxy.newProxyInstance(ConnectionDriver.class.getClassLoader(),
                new Class[] { Connection.class },new ConnectionHandler());
    }

    public static void main(String[] args) throws SQLException {
        Connection c = (Connection)Proxy.newProxyInstance(Object.class.getClassLoader(),
                new Class[]{Connection.class}, new ConnectionHandler());
        c.commit();
    }
}

